﻿ using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Reflection;
using System.Net;
using System.Net.Sockets;
using log4net;
using Koonsoft.Tool.SendMessage;

namespace Koonsoft.Tool.WatchService
{
    /// <summary>
    /// 扫描监听的端口列表
    /// </summary>
    public class ScanListenningPorts
    {
        private readonly static ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private static void CheckConfig()
        {
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["ListenPorts"]))
            {
                log.Warn("配置文件缺少ListenPorts节点", new Exception("请检查Config文件AppSettings项是否存在ListenPorts节点，并且该节点值不为空"));
            }

            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["TargetIP"]))
            {
                log.Warn("配置文件缺少TargetIP节点", new Exception("请检查Config文件AppSettings项是否存在TargetIP节点，并且该节点值不为空"));
            }
        }

        public static void ScanPorts()
        {
            CheckConfig();

            string targetIP = ConfigurationManager.AppSettings["TargetIP"];
            foreach (string s in ConfigurationManager.AppSettings["ListenPorts"].Split(','))
            {
                TcpClient tc = new TcpClient();
                tc.ReceiveTimeout = tc.SendTimeout = 2000;

                try
                {
                    tc.Connect(targetIP, Convert.ToInt32(s));
                    if (tc.Connected)
                    {
                        log.Info(string.Format("连接主机{0}，端口{1}成功。", targetIP, s));
                    }
                    else
                    {
                        log.Warn(string.Format("异常!主机{0}，端口{1}无法连接。", targetIP, s));

                        SendShortMessage.SendToSingleTarget("扫描WCF端口", string.Format("WCF服务端口{0}无法连接", s));                        
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
                finally
                {
                    tc.Close();
                    tc = null;
                }
            }
        }
    }
}
